//
//  ADLayout.swift
//  手账
//
//  Created by zhuxiaoxiang on 2018/11/17.
//  Copyright © 2018年 zhuxiaoxiang. All rights reserved.
//

import UIKit

class ADLayout: UICollectionViewFlowLayout {
    
    var delegate: ADLayoutProtocol!
    
    override func prepare() {
        super.prepare()
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
        itemSize = self.delegate.itemSize
        let inset = ((self.collectionView?.frame.size.width)! - self.delegate.itemSize.width) / 2
        sectionInset = UIEdgeInsetsMake(0, inset, 0, inset)
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.isPagingEnabled = false
    }
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var layoutAttributes: Array<UICollectionViewLayoutAttributes> = [UICollectionViewLayoutAttributes]()
        layoutAttributes = super.layoutAttributesForElements(in: rect)!
        var copyLayoutAttributes = [UICollectionViewLayoutAttributes]()
        let contentOffsetX = self.collectionView?.contentOffset.x;
        let collectionViewCenterX = self.collectionView!.frame.size.width * 0.5
        for layoutAttribute in layoutAttributes {
            let copyLayoutAttribute = layoutAttribute.copy() as! UICollectionViewLayoutAttributes
            let scale = 1 - fabs(copyLayoutAttribute.center.x - contentOffsetX! - collectionViewCenterX) / self.collectionView!.bounds.size.width / 2
            copyLayoutAttribute.transform = CGAffineTransform(scaleX: 1, y: scale)
            copyLayoutAttributes.append(copyLayoutAttribute)
        }
        return copyLayoutAttributes
    }
    
    override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        let rect = CGRect(x: proposedContentOffset.x, y: 0, width: self.collectionView!.bounds.size.width, height: self.collectionView!.bounds.size.height)
        let attrs = super.layoutAttributesForElements(in: rect)!
        var offset = proposedContentOffset
        let contentOffSetX = proposedContentOffset.x + self.collectionView!.frame.size.width / 2
        var minDistance = CGFloat(MAXFLOAT)
        for attr in attrs {
            let distance = attr.center.x - contentOffSetX
            if fabs(distance) < fabs(minDistance) {
                minDistance = distance
            }
        }
        offset.x += minDistance
        return offset
    }
}
